﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace EMoney.IStock.OAuth.Framework
{
    public class EncryptionUtil
    {
        /// <summary>
        /// 公钥私钥信息
        /// </summary>
        public static readonly string key = "<RSAKeyValue><Modulus>tXD+BESPJ4fmhXvnxdxvTszWb/aSKnsICUcWqMf/4M2q22jIcWzxUcrZyZoszii5GCsbO1KuWXhHASvmrmI1C7OELDr4U/SraOCGr8+e/Sh4XzkDjyWq/0LmC3v0JPOo9bM92ZaDa0mFrnxSwAPY3iSat2evHto4IhIgBZkTXL8=</Modulus><Exponent>AQAB</Exponent><P>7HIYskmXkk560kZPo05PKltur1sQvWEg2f52UkHK6Br6SVUcbvzmXemKzL+ZhvUEOeC4pNih0YWf7rqhziLKgQ==</P><Q>xHJfmjUTKQJNryIcGiNiYgBOLfxe6vk2GB48JkeXuRMccoII7148RyJYSNLLArEepMDpLnwBAhQHTHvoqfoHPw==</Q><DP>vfzgA0JG3HTbE+MTUrE1w188jQKrbMCC2Scyg94B4Ibs3cfZ1QS5RnTF5sd94Yc3IhqDw1GelPC+FeE46p3iAQ==</DP><DQ>IpN67jpvP+WO5MddKOCXfWZOXFuyHSt18PLJZXduZf3OIP1wMylj9KU/4rlvT+761Ma7hBoBV2tNCZI5lklSow==</DQ><InverseQ>jiI30UoHc0qODB+DzDYYw1tDiclfbUwh9kl/V/OYDzVx/eOeL5JQhMDBopPFcgsO0/ik77J9aU1KMCnRUdgYZA==</InverseQ><D>UUPHcc/nMjRrKjQhzfv6GpgiH0mXk9FA+y7M1lGlqGFVeioHRM4fk5vAScx07u1MYafE7aANmOMHIl4wVsCDsvUT5HoWIZYfoh6YJrLheLD2Hj3i7MOq4Yg1dlnScjCQ+dZjOKrCWC7aoiBmXVJw8HHZqzGkCVLJnoktT8mmwwE=</D></RSAKeyValue>";


        /// <summary>
        /// 解密一个String使用RSA
        /// </summary>
        /// <param name="input">被解密的对象</param>
        /// <param name="key">私钥</param>
        /// <param name="encodingUsing">编码格式</param>
        /// <returns>解密后的字符串</returns>
        public static string Decrypt(string input, Encoding encodingUsing = null)
        {
            if (string.IsNullOrEmpty(input))
            {
                return string.Empty;
            }
            else
            {
                try
                {
                    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                    {
                        encodingUsing = encodingUsing ?? Encoding.UTF8;
                        rsa.FromXmlString(key);
                        var encryptedBytes = rsa.Decrypt(Convert.FromBase64String(input), false);
                        rsa.Clear();

                        return encodingUsing.GetString(encryptedBytes);
                    }
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, string.Concat("RSA解密失败", input));

                    return string.Empty;
                }
            }
        }

        /// <summary>
        /// rsa 加密
        /// </summary>
        /// <param name="input"></param>
        /// <param name="encodingUsing"></param>
        /// <returns></returns>
        public static string Encrypt(string input, Encoding encodingUsing = null)
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                encodingUsing = encodingUsing ?? Encoding.UTF8;
                byte[] cipherbytes;
                rsa.FromXmlString(key);
                cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(input), false);
                rsa.Clear();
                return Convert.ToBase64String(cipherbytes);
            }
        }

        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="s"></param>
        /// <param name="key"></param>
        /// <param name="IV"></param>
        /// <returns></returns>
        public static String EncryptIt(String s, byte[] key, byte[] IV)
        {
            String result;
            RijndaelManaged rijn = new RijndaelManaged();
            rijn.Mode = CipherMode.ECB;
            rijn.Padding = PaddingMode.Zeros;
            rijn.KeySize = 128;
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (ICryptoTransform encryptor = rijn.CreateEncryptor(key, IV))
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(s);
                        }
                    }
                }
                result = Convert.ToBase64String(msEncrypt.ToArray());
            }
            rijn.Clear();
            return result;
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="s"></param>
        /// <param name="key"></param>
        /// <param name="IV"></param>
        /// <returns></returns>
        public static String DecryptIt(String s, byte[] key, byte[] IV)
        {
            String result;
            RijndaelManaged rijn = new RijndaelManaged();
            rijn.Mode = CipherMode.ECB;
            rijn.Padding = PaddingMode.Zeros;
            rijn.KeySize = 128;
            using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(s)))
            {
                using (ICryptoTransform decryptor = rijn.CreateDecryptor(key, IV))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader swDecrypt = new StreamReader(csDecrypt))
                        {
                            result = swDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            rijn.Clear();
            return result;
        }
    }
}
